<?php

namespace App\Service\Auth;

use App\Model\Service\NewGirlReplyPackageService;
use App\Service\BaseService;
use App\Constants\ErrorCode;
use App\Helpers\AliyunUtil;
use App\Helpers\ConfigUtil;
use App\Model\Message;
use App\Model\ProfileVerifyLog;
use App\Model\Service\CacheService;
use App\Model\UserProfile;
use App\Model\UserProfilePersonal;

/**
 * 阿里云-实名认证获取认证结果
 */
class AliVerfyResultService extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        $bizNo = $this->request->input('biz_no', '');
        $vrfyType = $this->request->input('vrfy_type', 1);

        //实人认证
        if ($vrfyType == 1) $vrfyKey = 'real_check';
        //真人头像对比
        elseif ($vrfyType == 2)  $vrfyKey = 'avatar_check';
        else {
            return $this->setError(ErrorCode::PARAMETER_ERROR, '参数传入有误，认证类型暂不支持！');
        }

        $profile = UserProfile::getProfile($userId, false);

        //验证结果
        $result = AliyunUtil::doVerifyResult($bizNo, $vrfyKey);
        if ($result->verifyStatus == -1) {
            log_user_result($userId, "NotComplete==verifyStatus:{$result->verifyStatus}");
            //修改认证状态
            // UserProfilePersonal::vrfyStatus($userId, UserProfilePersonal::STATUS_FAIL);
            return $this->setError(ErrorCode::VRF_NOT_COMPLT, '你还没有进行认证，请重新认证！');
        } elseif ($result->verifyStatus != 1) {
            log_user_result($userId, "VryFail==verifyResult==" . json_encode($result));
            //实人认证：修改认证状态
            $vrfyType == 1 && UserProfilePersonal::vrfyStatus($userId, UserProfilePersonal::STATUS_FAIL);
            //真人头像认证：认证不通过记录
            $vrfyType == 2 && ProfileVerifyLog::addRecord(
                $userId,
                ProfileVerifyLog::TYPE_REAL_AVATAR,
                ['avatar' => $profile->avatar],
                ProfileVerifyLog::STATUS_BAD
            );

            // 真人认证不通过后，女生角色修改
            if ($vrfyType == 2 && $profile->gender == 0) {
                UserProfile::where('user_id', $userId)->limit(1)->update(['role' => UserProfile::ROLE_USER]);
            }

            return $this->setError(ErrorCode::VRF_FAIL, '认证不通过，请尝试重新认证！', ['vrf_code' => $result->verifyStatus]);
        }
        //其他操作
        $this->otherBusi($userId, $result, $vrfyType, $profile);
        log_user_result($userId, "VrySucc==verifyResult==" . json_encode($result));
        return [
            'result' => 1,
            'facePic' => $result->material->faceImageUrl ?? '',
        ];
    }

    /**
     * 其他业务处理
     */
    function otherBusi($userId = 0, $result = null, $vrfyType = 1, $profile = null)
    {
        //修改认证状态
        $idCardInfo = $result ? $result->material->idCardInfo : null;
        $facePic = $result ? $result->material->faceImageUrl : '';
        //照片存储，保存
        $picName = time() . "_{$userId}.jpg";
        $uploadFile = AliyunUtil::uploadRemotePhoto($facePic, $picName);
        switch ($vrfyType) {
                //真人头像认证
            case 2:
                //图片认证
                UserProfile::where('user_id', $userId)->limit(1)->update(['avatar_vrfy' => 1]);
                //认证时间
                UserProfilePersonal::vrfyStatus($userId, -1, $uploadFile, $idCardInfo);
                //提交审核记录
                ProfileVerifyLog::addRecord(
                    $userId,
                    ProfileVerifyLog::TYPE_REAL_AVATAR,
                    ['avatar' => $profile->avatar, 'real_avatar' => $uploadFile],
                    ProfileVerifyLog::STATUS_OK
                );

                // 真人认证后，女生角色修改
                if ($profile->gender == 0) {
                    $newGirlTaskValid = config('act.new_girl_task_valid', '2023-03-12');
                    if ($profile->created_at >= $newGirlTaskValid) {
                        NewGirlReplyPackageService::realAvatar((int)$userId);
                    }

                    UserProfile::where('user_id', $userId)->limit(1)->update(['role' => UserProfile::ROLE_HOST]);
                }

                break;

                //实人认证
            case 1:
                UserProfilePersonal::vrfyStatus($userId, UserProfilePersonal::STATUS_OK, $uploadFile, $idCardInfo);
                //修改主播身份，设置默认收费值（语音和视频）
//                $voiceSet = CacheService::getCoinSetting('voice_coin_setting');
//                $videoSet = CacheService::getCoinSetting('video_coin_setting');
//                $info = [
//                    'role' => UserProfile::ROLE_HOST,
//                    'host_time' => time(),
//                    'coin_setting' => $voiceSet[0]['coin'] ?? 10,
//                    'video_coin_setting' => $videoSet[0]['coin'] ?? 20,
//                    'chat_coin_setting' => 2,
//                ];
//                UserProfile::updateInfo($userId, $info);
                //发送站内信
                Message::pushHostVerify($userId);
                //小助手欢迎信
                Message::officialImMsg($userId, 'host');
                break;
        }
        return;
    }
}
